package com.datastructure.test.thirtysixadd;

public class ThirtySixAdd {

    public static void main(String[] args) {
        ThirtySixAdd thirtySixAdd = new ThirtySixAdd();
        String thirtysixAdd = thirtySixAdd.thirtysixAdd("z", "1");
        System.out.println(thirtysixAdd);
    }

    public String thirtysixAdd (String A, String B) {
        // write code here
        int aLength = A.length();
        int bLength = B.length();
        StringBuilder stringBuilder = new StringBuilder(A);
        A = stringBuilder.reverse().toString();
        stringBuilder = new StringBuilder(B);
        B = stringBuilder.reverse().toString();
        char[] charsA = A.toCharArray();
        int[] intA = new int[aLength];
        for (int i = 0; i < charsA.length; i++) {
            if(Character.isLetter(charsA[i])){
                intA[i]=charsA[i]-87;
            }else {
                intA[i]=charsA[i]-48;
            }
        }
        char[] charsB = B.toCharArray();
        int[] intB = new int[bLength];
        for (int i = 0; i < charsB.length; i++) {
            if(Character.isLetter(charsB[i])){
                intB[i]=charsB[i]-87;
            } else {
                intB[i]=charsB[i]-48;
            }
        }
        int i = 0;
        int j = 0;
        int positive = 0;
        int surplus;
        stringBuilder = new StringBuilder();
        while (i<aLength&&j<bLength){
            surplus = (positive+intA[i]+intB[j])%36;
            positive = (positive+intA[i]+intB[j])/36;
            if(surplus<=9){
                stringBuilder.append(surplus);
            } else {
                stringBuilder.append((char) (surplus+87));
            }
            i++;
            j++;
        }
        if(i==aLength){
            while (j<bLength){
                surplus = (positive+intB[j])%36;
                positive = (positive+intB[j])/36;
                if(surplus<=9){
                    stringBuilder.append(surplus);
                } else {
                    stringBuilder.append((char) (surplus+87));
                }
                j++;
            }
        } else {
            while (i<aLength){
                surplus = (positive+intA[i])%36;
                positive = (positive+intA[i])/36;
                if(surplus<=9){
                    stringBuilder.append(surplus);
                } else {
                    stringBuilder.append((char) (surplus+87));
                }
                i++;
            }
        }
        if(positive!=0){
            stringBuilder.append(positive);
        }
        return stringBuilder.reverse().toString();
    }
}
